<template>
	<view class="chatInterface">
		<uni-list :border="false" class="chat-list">
			<view class="message-item" v-for="(item,index) in messages">
				<view v-if="item.contentType >=200" class="tip">
					<view>{{messageJson(item).tip}}</view>
				</view>
				<view v-else class="chat" :style="{
					'direction' : switchStyle(item)? 'rtl':'ltr'
				}">
					<image class="avatar" :src="item.senderFaceUrl">
					</image>
					<view class="content" :style="{
					'background-color' : switchStyle(item)? '#40E0D0':'#9370DB'
				}">
						<image v-if="item.contentType ==102" class="msgImage" :src="messageJson(item).thumb"
							></image>
						<view v-if="item.contentType ==101" class="text">{{
							messageJson(item).content
						}}</view>
						<view v-if="item.contentType ==103" class="msgAudio" @click="playAudio(item)">
							<!-- <image src="../../static/voice_other.png" class="voice"></image> -->
							<view :class="classAnima"></view>
							<view class="voice-text">{{item.soundElem.duration +'”'}}</view>
						</view>
					</view>
				</view>
			</view>
		</uni-list>
		<view class="bottom-white"></view>
		<view class="bottom-bar">
			<view class="bar-list">
				<image src="../../static/voice.png" class="typeIcon" />
				<view></view>
				<input confirm-type="send" @confirm="sendTextMsg" v-model="inputValue" placeholder="请输入..."
					class="bottom-input" />
				<image v-if="inputValue.trim().length==0" class="typeIcon" @click="moreAction"
					src="../../static/moreOperation.png" />
				<view v-else class="bottom-btn" @click="sendTextMsg">发送</view>
			</view>
		</view>
	</view>
</template>

<script>
	import * as opIm from '../../utils/openIm.js';
	import {
		date
	} from '../../utils/time.js'
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	export default {
		name: "privateChat",
		data() {
			return {
				targetId: '',
				groupId:'',
				messages: [],
				testm: [],
				inputValue: '',
				myInfo: {},
				voicePath: '',
				classAnima : 'bg'
			}
		},
		onShow() {

		},
		onLoad(options) {
			this.myInfo = uni.getStorageSync('myInfo');
			console.log(this.myInfo);
			this.targetId = options.targetId;
			this.groupId = options.groupId;
			// 进入标记已读
			opIm.markSingleMessageRead(this.targetId,this.groupId);
			uni.startPullDownRefresh();
			setTimeout(() => {
				this.scrollToBottom();
			}, 500)

			// 监听IM 收到消息
			opIm.openIM.on('OnRecvNewMessage', (data) => {
				// 如果是当前用户则插入
				console.log('新消息监听到');
				let msg = JSON.parse(data.data)
				console.log(msg);
				if (msg.sendID == this.targetId && msg.contentType <= 110) {
					// 这是单聊
					this.messages = this.messages.concat(msg);
				}else if(msg.groupID == this.groupId && msg.contentType <=101 && msg.groupID != ''){
					this.messages = this.messages.concat(msg);
				}
			});

			recorderManager.onStop(function(res) {
				console.log('recorder stop' + JSON.stringify(res));
				this.voicePath = res.tempFilePath;
			});
		},
		onPullDownRefresh() {
			// uni.stopPullDownRefresh();
			console.log('refresh');
			this.getHistoryMessage(this.targetId,this.groupId);
		},
		methods: {
			playAudio(item){
					// 播放语音
					console.log('播放录音');
					if (item.soundElem.sourceUrl) {
						innerAudioContext.src = item.soundElem.sourceUrl;
						innerAudioContext.play();
						this.classAnima = 'bg voicePlay';
					}
					
					innerAudioContext.onEnded(function(_){
						//
						console.log('结束');
						this.classAnima = 'bg voicePlay_Paused';
					})
			},
			startRecord() {
				console.log('开始录音');
				RecorderManager.start();
			},
			endRecord() {
				console.log('录音结束');
				recorderManager.stop();
			},
			playVoice() {
				
			},
			switchStyle(item) {
				if (item.sendID == this.myInfo.uid && item.contentType < 200) {
					return true;
				} else {
					return false
				}
			},
			getHistoryMessage(targetId,groupId) {
				let index = this.messages.length;
				let last = index <= 0 ? null : this.messages[0];
				console.log(last);
				opIm.getHistoryMessages(targetId,last,groupId).then((res) => {
					let ll = JSON.parse(res.data);
					//删除重复的	
					let pp = ll.concat(this.messages);
					// if(last !=null) pp.remove(last);
					this.messages = pp;
					console.log(this.messages);
					uni.stopPullDownRefresh();
				}).catch((err) => {})
			},
			messageJson(item) {
				switch (item.contentType) {
					case 101:
						return {
							'isText': true,
							'content': item.content
						};
						break;
					case 102:
						return {
							'isImage': true,
							'content': item.content,
								'thumb': item.pictureElem.snapshotPicture.url,
								'ori': item.pictureElem.sourcePicture.url,
								'thumbWidth': item.pictureElem.snapshotPicture.width,
								'thumbHeight': item.pictureElem.snapshotPicture.height,
						};
						break;
					case 103:
						break;
					case 104:
						break;
					case 105:
						break;
					case 109:
						break;
					case 201:
						let content = JSON.parse(item.content);
						return {
							'isTip': true,
							'tip': content.defaultTips
						};
						break;
					default:
						break;
				}

			},
			//渲染文本消息，如果包含表情，替换为图片
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			initRecorderListeners() {
				// 监听录音开始
				recorderManager.onStart(() => {
					this.audio.recording = true;
				});
				//录音结束后，发送
				recorderManager.onStop((res) => {
					this.sendMessage(audioMessage);
				});
				// 监听录音报错
				recorderManager.onError(function(res) {
					console.log("录音报错：", res);
				})
			},
			sendMessage(message) {
				console.log('发送');
				opIm.sendTextMessage(message, this.targetId).then((res) => {
					// console.log(res);
					this.messages = this.messages.concat(JSON.parse(res));
					this.scrollToBottom();
					opIm.sendMessage(res, this.targetId);
				});
			},
			sendTextMsg() { //发送消息
				if (this.inputValue.trim() !== '') {

					this.sendMessage(this.inputValue);
				}
				this.inputValue = "";
			},
			//语音录制按钮和键盘输入的切换
			switchAudioKeyboard() {
				this.audio.visible = !this.audio.visible;
				if (uni.authorize) {
					uni.authorize({
						scope: 'scope.record'
					})
				}
			},
			onRecordStart() {
				try {
					recorderManager.start();
				} catch (e) {
					uni.showModal({
						title: '录音错误',
						content: '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
					});
				}
			},
			onRecordEnd() {
				try {
					recorderManager.stop();
				} catch (e) {
					console.log(e)
				}
			},
			sendImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						let imageMessage = this.goEasy.im.createImageMessage({
							to: {
								id: this.friend.uuid,
								type: this.GoEasy.IM_SCENE.PRIVATE,
								data: {
									name: this.friend.name,
									avatar: this.friend.avatar
								}
							},
							file: res,
							onProgress: function(progress) {
								console.log(progress)
							},
							notification: {
								title: this.currentUser.name + '发来一张图片',
								body: '[图片消息]' // 字段最长 50 字符
							}
						});
						this.sendMessage(imageMessage);
					}
				});
			},
			showImageFullScreen(e) {
				var imagesUrl = [e.currentTarget.dataset.url];
				uni.previewImage({
					urls: imagesUrl
				});
			},
			scrollToBottom() {
				this.$nextTick(function() {
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration: 10
					})
				});
			},
		}
	}
</script>

<style lang="scss">
	.message-item {
		margin: 24rpx 0;

	}

	.bottomType {
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 160px;
	}

	.chat {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 0 30rpx;
	}

	.bottom-white {
		height: 100rpx;
	}

	.content {
		border-radius: 10rpx;
		padding: 5px;
		margin: 0 24rpx;
		color: white;
		max-width: 500rpx;
		direction: 'ltr';
	}

	.msgImage {
		max-width: 500rpx;
		max-height: 600rpx;
	}

	.tip {
		background-color: #909399;
		color: #F0AD4E;
		max-width: 500rpx;
		border-radius: 18rpx;
		padding: 5px;
		margin: auto;
	}

	.chatInterface {
		width: 100%;
		height: 100%;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.msgAudio {
		display: flex;
		align-items: center;
	}

	.voice {
		width: 24rpx;
		height: 24rpx;
	}

	.voice-text {
		margin: 0 6px;
	}

	.bottom-bar {
		display: flex;
		flex-direction: column;
		justify-content: center;
		position: fixed;
		bottom: 0;
		width: 100%;


		.typeIcon {
			width: 50rpx;
			height: 50rpx;
		}

		.reply-msg {
			padding-left: 24rpx;
			height: 20px;
			background-color: #e8f2ff;
		}

		.bar-list {
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding: 16rpx 0;
			background-color: #e8f2ff;

			.bottom-input {
				background-color: #FFFFFF;
				border-radius: 12rpx;
				height: 60rpx;
				width: 70%;
			}

			.bottom-btn {
				color: #FFFFFF;
				background-color: #1b72ec;
				font-size: 28rpx;
				margin-right: 16rpx;
			}

			.u-icon {
				margin: 0 16rpx;
			}
		}
	}



	.voice {
		padding-top: 12px;
		padding-left: 10px;
		margin: 100px auto;
		height: 35px;
		width: 150px;
		background: #1bbc9b;
		border-radius: 0 7px 7px;
	}

	.bg {
		background: url() right 0 no-repeat;
		width: 24px;
		height: 24px;		
	}

	.voicePlay {
		animation-name: voicePlay;
		animation-duration: 1s;
		animation-direction: normal;
		animation-iteration-count: infinite;
		animation-timing-function: steps(3);
	}
	
	.voicePlay_Paused {
		animation-play-state: paused;
	}
	
	@keyframes voicePlay {
		0% {
			background-position: 0%;
		}

		100% {
			background-position: 100%;
		}
	}
</style>
